import jwt

from rest_framework.authentication import BaseAuthentication
from jwt import exceptions
from django.conf import settings
from rest_framework.response import Response
from rest_framework.exceptions import AuthenticationFailed

"""================用于认证===================="""


class jwtHeaderAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        salt = settings.SECRET_KEY
        payload = None
        detail = None
        try:
            payload = jwt.decode(token, salt, True)
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({"detail": 'token已失效'})
        except exceptions.DecodeError:
            raise AuthenticationFailed({"detail": 'token认证失败'})
        except exceptions.InvalidTokenError:
            raise AuthenticationFailed({"detail": 'token非法'})

        return (payload, token)
